var BrowserSupp = {}, Tigi = {},
	player, selects = [], scroll;

window.addEvent('domready', function(){
	
	// Browser Features
	Tigi.BrowserSupport();
	
	// Full width Pushbox
	var pushbox = $('pushbox');
	if (pushbox){
		new Tigi.Pushbox({
			wrapper: pushbox,
			items: pushbox.getElements('ul.items li'),
			buttons: pushbox.getElements('nav ul li a')
		});
	}
	
	// Toggle a div on Click
	Tigi.ToggleElm($$('a.toggleElm'));
	Tigi.ToggleElmDefault($$('a.toggleElmDefault'));
	
	// Slide and Element In/Out on Click
	Tigi.SlideElm($$('a.slideElm'));
	
	// Team Mouseovers
	Tigi.Team($$('ul.team li a'));
	var fh = 116;
	if (Browser.ie){ fh = 102; };
	Tigi.Team($$('article.product-list .site li a'), fh);
	
	// Equal Column Heights
	Tigi.EqualColumns($$('.equalColumn'));
	
	// Brands Accordion
	$$('ul.brands').each(function(wrapper, i){
		new Tigi.Brands({
			items: wrapper.getElements('> li'),
			defaultItems: wrapper.getElements('> li div.default')
		});
	});
	
	// Tweet Slider
	$$('ul.tweets').each(function(wrapper, i){
		new Tigi.TweetSlider({
			items: wrapper.getElements('li'),
			time: wrapper.getNext('p.time')
		});
	});
	
	Tigi.ToggleFormRegistration($$('form.register fieldset.options input[type=radio]'), $$('form.register fieldset.other')[0], 'False');
	
	// Activate Label on input Change event
	$$('fieldset.brands').each(function(fieldset, i){
		Tigi.ActiveLabel(fieldset.getElements('input'), fieldset.getElements('label'));
	});
	
	var newsArchive = $('news-archive');
	if (newsArchive){
		new Tigi.NewsArchive({
			wrapper: newsArchive,
			form: newsArchive.getElement('form'),
			input: newsArchive.getElement('form input'),
			result: newsArchive.getElement('ul.result'),
			pager: newsArchive.getElement('ul.pager')
		});
	}
	
	$$('.interview-slider').each(function(wrapper, i){
		new Tigi.ArticleSlider({
			wrapper: wrapper,
			articles: wrapper.getElements('article.interview'),
			pager: wrapper.getParent().getElements('ul.pager-fixed li a'),
			lblCurrent: wrapper.getParent().getElements('ul.pager-fixed li span.current'),
			lblTotal: wrapper.getParent().getElements('ul.pager-fixed li span.total')
		});
	});
	
	var videoplayer = $('videoplayer-wrapper');
	if (videoplayer){
		player = new Tigi.VideoPlayer({
			wrapper: videoplayer,
			playerWrapper: videoplayer.getElement('#videoplayer'),
			player: videoplayer.getElement('#player'),
			controls: videoplayer.getElement('.controls')
		});
	}
	
	$$('input.autocomplete').each(function(input, i){
		new Tigi.AutoComplete(input, {
			onComplete: function(obj){
				if (input.get('name') == 'salon-name'){
					Object.each(obj, function(salon, i){
						var inp = $('inp-salon-' + i);
						if (inp){ inp.set('value', salon); }
					});
				}
			}
		});
	});
	
	$$('.scroll-page').each(function(wrapper, i){
		scroll = new Tigi.Scrollpage({
			wrapper: wrapper,
			nav: wrapper.getElement('nav.sub'),
			buttons: wrapper.getElements('nav.sub ul li a')
		});
	});
	
	Tigi.Accordion('dl.accordion');
	
	Tigi.Formulas('.formula-list li a');
	Tigi.LoadFormulas('.load-formulas');	
	Tigi.FormulasMoreInfo('.formula-more-info > li');
	
	new Tigi.InnerPageScroll({
		container: $(document.body),
		links: $$('.scroll-link')
	});
	
	$$('.fullheight').each(function(wrapper, i){
		Tigi.FullHeight(wrapper);
	});
	
	Tigi.HeaderSlide($$('body > header a.right'), $$('body > header'));
	
	$$('form').each(function(form, i){
		new Tigi.FormValidation(form);
	});

});

// Form Validation for Forms
Tigi.FormValidation = new Class({
	options: {
		form: null,
		validator: null
	},
	Implements: Options,
	initialize: function(form, options){
		this.setOptions(options);
		this.options.form = form;
		
		this.findValidators();
	},
	findValidators: function(){
		this.setRequired(this.options.form.getElements('[data-val-required]'));
		this.setDigits(this.options.form.getElements('[data-val-number]'));
		this.setEmail(this.options.form.getElements('[data-val-email]'));
		this.setRegex(this.options.form.getElements('[data-val-regex]'));
		this.setRange(this.options.form.getElements('[data-val-range]'));
		
		this.options.form.getElements('input, textarea').each(function(inp, i){
			inp.addEvent('blur', function(){
				this.trimValue(inp);
			}.bind(this))
		}, this);
		
		this.setValidation();
	},
	setRequired: function(inputs){
		inputs.addClass('required');
	},
	setEmail: function(inputs){
		inputs.addClass('validate-email');
	},
	setRegex: function(inputs){
		inputs.each(function(inp, i){
			inp.addClass('validate-regex-' + inp.get('name'));
		});
	},
	setDigits: function(inputs){
		inputs.addClass('validate-integer');
	},
	setRange: function(inputs){
		inputs.addClass('validate-range');
	},
	setValidation: function(){
		this.setEmailValidation();
		this.setReqexValidation();
		this.setRangeValidation();
		
		this.options.validator = new Form.Validator(this.options.form, {
			ignoreHidden: false,
			onElementPass: function(elm){
				var span = elm.getNext('span[data-id="' + elm.get('id') + '"]');
				if (elm.hasClass('validate-custom-select')){
					elm.getNext('a').removeClass('validation-failed');
					span = elm.getParent('div').getNext('span[data-id="' + elm.get('id') + '"]');
				}				
				if (span){ span.dispose(); }
				
				this.trimValue(elm);
			}.bind(this),
			onElementFail: function(elm, error){
				this.trimValue(elm);				
				
				var span = elm.getNext('span[data-id="' + elm.get('id') + '"]'), 
					inject = elm;
				if (elm.hasClass('validate-custom-select')){
					elm.getNext('a').addClass('validation-failed');
					span = elm.getParent('div').getNext('span[data-id="' + elm.get('id') + '"]');
					inject = elm.getParent('div');
				}
				
				if (!span && !elm.hasClass('s')){					
					span = new Element('span', {
						'data-id': elm.get('id'),
						'class': 'field-validation-error'
					}).inject(inject, 'after');
				}
				
				var dataVal = error[0];
				switch (error[0]){
					case 'validate-email': dataVal = 'email'; break;
					case 'validate-digits': dataVal = 'number'; break;
					case 'validate-range': dataVal = 'range'; break;
				}
				if (!span || !elm.get('data-val-' + dataVal)){ return false; }
				span.set('html', elm.get('data-val-' + dataVal));
			}.bind(this)
		});
	},
	setEmailValidation: function(){
		var msg = 'This is not a valid E-mail address';
		if (this.options.form.getElements('[data-val-email]')[0]){
			msg = this.options.form.getElements('[data-val-email]')[0].get('data-val-email');
		}
		Form.Validator.add('validate-email', {
			errorMsg: msg,
			test: function(inp){
				if (!inp.hasClass('required') && inp.get('value').length < 1){ return true; }
				var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
			    return pattern.test(inp.get('value'));
			}
		});
	},
	setReqexValidation: function(){
		this.options.form.getElements('[data-val-regex]').each(function(inp, i){
			Form.Validator.add('validate-regex-' + inp.get('name'), {
				errorMsg: inp.get('data-val-regex'),
				test: function(inp){
					if (!inp.hasClass('required') && inp.get('value').length < 1){ return true; }
					var pattern = new RegExp(inp.get('data-val-regex-pattern'));
				    return pattern.test(inp.get('value'));
				}
			});
		});
	},
	setRangeValidation: function(){
		var elms = this.options.form.getElements('[data-val-range]');
		Form.Validator.add('validate-range', {
			errorMsg: (elms[0] ? elms[0].get('data-val-range') : 'This is not a valid input'),
			test: function(inp){
				if (!inp.hasClass('required') && inp.get('value').length < 1){ return true; }
				
				var value = inp.get('value').toInt(),
					minValue = (inp.get('data-val-range-min') ? inp.get('data-val-range-min').toInt() : null),
					maxValue = (inp.get('data-val-range-max') ? inp.get('data-val-range-max').toInt() : null);
					
				if (minValue != null && maxValue != null){
					return value >= minValue && value <= maxValue;
				}
				else if(minValue != null){
					return value >= minValue;
				}
				else if(maxValue != null){
					return value <= maxValue;
				}				
				return true;
			}
		});
	},
	trimValue: function(elm){
		var curValue = elm.get('value'),
			newValue = elm.get('value').trim();
		
		elm.set('value', newValue);	
		if (curValue != newValue){
			this.options.validator.validateField(elm);
		}
	}
});

// Slide new Header in on Click Button
Tigi.HeaderSlide = function(btns, headers){
	btns.each(function(btn, i){
		headers[i].set('tween', { duration: 600 });
		btn.addEvent('click', function(e){
			e.stop();
			headers[i].set('tween', {
				onComplete: function(){
					this.element.removeClass('inactive');
					document.location.href = btn.get('href');
				}
			});			
			var w = $(window).getSize().x.toInt();
			headers.each(function(header, j){
				header.addClass('inactive');
				if (i == j){
					header.tween('left', (btn.get('data-to') == 'rgt' ? w : -w));
				}
				else {
					header.tween('left', [(btn.get('data-to') == 'rgt' ? -w : w), 0]);
				}
			});
		});
	});
}

// Browser Support (Placeholder, CSS Columns, Checkboxes & Radio Buttons, Select)
Tigi.BrowserSupport = function(){
	BrowserSupp.Placeholder();
	if ($(document.html).hasClass('no-csscolumns')){
		var elms = $$('.col-wrapper, .triple-col-wrapper');
		if (elms.length > 0){
			new MM.Columnizr(elms);
		}
	}
	new BrowserSupp.Checkbox($$('input.custom-radio, input.custom-checkbox'));
	$$('select.custom').each(function(select, i){
		selects.push(new BrowserSupp.Select(select, i));
	});
	
	BrowserSupp.Pseudos('.product-information ul li', 'before', '—');
	
	if (Browser.ie7){
		$$('table a table').each(function(table, i){
			table.addEvent('click', function(e){
				document.location.href = this.getParent('a').get('href');
			});
		});
		
		$$('ul.steps li').addClass('equalColumn');
	}
}

// AutoComplete
Tigi.AutoComplete = new Class({
	options: {
		wrapper: null,
		input: null,
		result: null,
		searchUrl: '',
		value: '',
		req: null,
		click: false,
		open: false,
		onComplete: null
	},
	Implements: [Options, Events],
	initialize: function(input, options){
		this.setOptions(options);
		this.options.input = input;
		
		this.create();
	},
	create: function(){
		this.options.wrapper = new Element('div', { 'class': 'autocomplete-wrapper' }).wraps(this.options.input);		
		this.options.result = new Element('ul', { 'class': 'autocomplete-result' }).inject(this.options.wrapper);
			
		this.setRequest();
		this.addEvents();
	},
	setRequest: function(){
		this.options.req = new Request.JSON({
			url: this.options.input.get('data-url'),
			onComplete: function(json){
				this.setResults(json);
			}.bind(this)
		});
	},
	addEvents: function(){
		this.options.input.addEvents({
			focus: function(){
				var val = this.options.input.get('value');
				if (val.length > 3){
					//this.open();
				}
			}.bind(this),
			keyup: function(){
				var val = this.options.input.get('value');
				if (val.length > 3 && val != this.options.value){
					this.options.value = val;
					this.find();
				}
				else if(val.length < 4) {
					this.options.value = '';
					this.options.result.empty();
					this.close();
				}
			}.bind(this)
		});
		
		this.options.wrapper.addEvent('click', function(){
			this.options.click = true;
		}.bind(this));
		
		$(window).addEvents({
			click: function(){
				if (!this.options.click){ this.close(); }
				this.options.click = false;
			}.bind(this)
		});
		$(document.body).addEvents({
			keydown: function(e){
				if (e.key == 'enter'){ e.stop(); }
			},
			keyup: function(e){
				if (this.options.open){
					switch (e.key){
						case 'down': {
							this.next();
							break;
						}
						case 'up': {
							this.prev();
							break;
						}
						case 'enter': {
							e.stop();
							this.select();
							break;
						}
					}
				}
			}.bind(this)
		});
	},
	setResults: function(json){
		this.options.active = 0;
		this.options.result.empty();
		
		json.salons.each(function(salon, i){
			var li = new Element('li', {
				'html': salon.name,
				'class': (i == this.options.active ? 'active' : null),
				'events': {
					click: function(){
						//this.options.input.set('value', salon.name);
						this.options.value = salon.name;
						this.fireEvent('complete', salon);
						this.close();
					}.bind(this),
					mouseenter: function(){
						this.options.active = i;
						this.options.result.getElements('li.active').removeClass('active');
						li.addClass('active');
					}.bind(this)
				}
			}).inject(this.options.result);
		}, this);
		
		this.open();
	},
	find: function(){
		this.options.req.get({ 'val': this.options.value });
	},
	open: function(){
		this.options.open = true;
		this.options.result.setStyle('display', 'block');
	},
	close: function(){
		this.options.open = false;
		this.options.result.setStyle('display', 'none');
	},
	prev: function(){
		var items = this.options.result.getElements('li');
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = items.length - 1;
		}
		this.activate();
	},
	next: function(){
		var items = this.options.result.getElements('li');
		++this.options.active;
		if (items.length - this.options.active < 1){
			this.options.active = 0;
		}
		this.activate();
	},
	activate: function(){
		var items = this.options.result.getElements('li');
		items.removeClass('active');
		items[this.options.active].addClass('active');
	},
	select: function(){
		this.options.result.getElements('li')[this.options.active].fireEvent('click');
	}
});

// HTML5/SWF VideoPlayer
Tigi.VideoPlayer = new Class({
	options: {
		wrapper: null,
		playerWrapper: null,
		player: null,
		controls: null,
		fullScreen: null,
		expanded: false,
		currentFlashTime: 0,
		html: $(document.html),
		defaultParent: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);		
		this.create();
		
		this.options.defaultParent = this.options.wrapper.getParent();
		
		//this.options.html.removeClass('video').addClass('no-video');
		if(this.options.html.hasClass('no-video')) {
			if (swfobject.getFlashPlayerVersion().major == '0'){
				new Element('div', { 'class': 'no-flash', 'html': 'There is no flash player installed.<br />Install Flash player to view this movie.' }).inject(this.options.player.getParent());
				this.options.player.dispose();
				this.options.controls.dispose();
				return false;
			}
			this.initFlashPlayer();
		}
		
		this.initVolume();
		this.addEvents();
	},
	create: function(){
		this.options.fullScreen = new Element('div', { 'class': 'fullscreen-wrapper' }).inject($(document.body));
	},
	addEvents: function(){
		this.options.wrapper.addEvents({
			mouseenter: function() {
				this.showControls();
			}.bind(this),
			mouseleave: function() {
				this.hideControls();
			}.bind(this)
		});
		
		this.options.controls.getElements('a').each(function(el) {
			el.addEvent('click', function(e) {
				e.stop();
				if(el.hasClass('play')) {
					this.playVideo();
				} else if(el.hasClass('pause')) {
					this.pauseVideo();
				} else if(el.hasClass('fullscreen')) {
					this.toggleFullscreen();
					this.playVideo();
				}
			}.bind(this));
		}, this);
		
		this.addProgressEvents();
		this.addVolumeEvents();
		
		if(this.options.html.hasClass('video')) {
			this.options.player.addEventListener('timeupdate', function(){
				this.setProgressbar(Math.round(this.options.player.currentTime));
			}.bind(this), false);
			
			this.options.player.addEventListener('ended', function(){
				this.options.player.currentTime = 0;
				this.pauseVideo();
				
				playerEnded(['_trackEvent', 'About', 'VideoFinished']);
			}.bind(this), false);
			
			this.pauseVideo();
		}
	},
	addProgressEvents: function(){
		var progressDown = false;
		this.options.controls.getElement('.progressbar .progress').addEvents({
			mousedown: function(e){
				progressDown = true;
				this.scrubProgress(e.page.x);
			}.bind(this),
			mousemove: function(e){
				if (progressDown){
					this.scrubProgress(e.page.x);
				}
			}.bind(this),
			mouseup: function(e){
				progressDown = false;
				this.scrubProgress(e.page.x);
			}.bind(this)
		});
		this.options.controls.getElement('.progressbar').addEvents({
			mouseenter: function(){
				this.getElement('.progress').set('morph', { duration: 150, link: 'cancel' }).morph({
					'height': 5,
					'marginTop': 0,
					'marginBottom': 0
				});
			},
			mouseleave: function(){
				this.getElement('.progress').morph({
					'height': 1,
					'marginTop': 2,
					'marginBottom': 2
				});
			}
		});
	},
	addVolumeEvents: function(){
		var volumeDown = false;
		this.options.controls.getElement('.volume').addEvents({
			mousedown: function(e){
				volumeDown = true;
				this.scrubVolume(e.page.x);
			}.bind(this),
			mousemove: function(e){
				if (volumeDown){
					this.scrubVolume(e.page.x);
				}
			}.bind(this),
			mouseup: function(e){
				volumeDown = false;
				this.scrubVolume(e.page.x);
			}.bind(this)
		});
	},
	initFlashPlayer: function(){
		var params = {
			quality : 'high',
			scale : 'noscale',
			wmode : 'transparent',
			allowscriptaccess : 'always',
			bgcolor : '#000000'
		};
		var flashvars = {
			videoURL: '../../' + this.options.player.getElement('source').get('src'),
			posterImage: (this.options.player.get('poster') ? this.options.player.get('poster') : '')
		};	
		var attributes = {
			id : this.options.player.get('id'),
			name : this.options.player.get('id')
		};
		
		var dim = this.options.player.measure(function(){
			return this.getSize();
		});
		
		swfobject.embedSWF('inc/swf/player.swf', this.options.player.get('id'), dim.x, dim.y, '10.0.0', 'Error/NotFound2086.html', flashvars, params, attributes);
	},
	updateTimer: function(t) {
		var s = t;
        s = s % 3600;
        var m = Math.floor(s / 60);
        s = Math.floor(s % 60);
        if (s.toString().length < 2)
            s = '0' + s;
        if (m.toString().length < 2)
            m = '0' + m;
			
        //this.options.controls.getElement('time').set('html', m + ':' + s);
	},
	videoTimeUpdate: function(time) {
		if(this.options.currentFlashTime != Math.round(time)) {
			//this.updateTimer(time);
			this.options.currentFlashTime = Math.round(time);
			this.setProgressbar(Math.round(time));
		}
	},
	playVideo: function() {
		this.options.controls.getElement('a.pause').removeClass('pause-active');
		this.options.controls.getElement('a.play').addClass('play-active');
		if(this.options.html.hasClass('video')){
			this.options.player.play();
		} else {
			if (BrowserSupp.getFlashMovieObject(this.options.player.get('id'))){
				BrowserSupp.getFlashMovieObject(this.options.player.get('id')).playVideo();
			}
		}
	},
	pauseVideo: function() {
		this.options.controls.getElement('a.play').removeClass('play-active');
		this.options.controls.getElement('a.pause').addClass('pause-active');
		if(this.options.html.hasClass('video')) {
			this.options.player.pause();
		} else {
			if (BrowserSupp.getFlashMovieObject(this.options.player.get('id'))){
				BrowserSupp.getFlashMovieObject(this.options.player.get('id')).pauseVideo();
			}
		}
	},
	setProgressbar: function(currentTime) {
		var progressWidth = this.options.controls.getElement('.progress').getSize().x;
		this.options.controls.getElement('.progress span').setStyle('width', progressWidth / Math.round(this.options.player.duration) * currentTime);
	},
	scrubProgress: function(pageX) {
		var progressWidth = this.options.controls.getElement('.progress').getSize().x,
			offset = pageX - this.options.controls.getElement('.progress').getPosition().x,
			percentage = progressWidth / offset;
			
		var curTime = this.options.player.duration / percentage;
		
		if(this.options.html.hasClass('video')){
			this.options.player.currentTime = curTime;
		}
		else {
			BrowserSupp.getFlashMovieObject(this.options.player.get('id')).updatePlayHead(curTime);
		}
		
		this.setProgressbar(Math.round(curTime));
	},
	initVolume: function(){
		var playerVol = this.options.player.volume,
			volPerc = playerVol * 10;
		this.options.volElms = this.options.controls.getElements('.volume span');
		this.options.volElms.each(function(elm, i){
			if (i <= volPerc){
				elm.addClass('active');
			}
		});
		
		this.options.volumeWidth = this.options.controls.getElement('.volume').measure(function(){
			return this.getSize().x;
		});
	},
	scrubVolume: function(pageX) {
		var offset = pageX - this.options.controls.getElement('.volume').getPosition().x,
			percentage = offset / this.options.volumeWidth;
		
		if (percentage > 1){ percentage = 1; }
		else if (percentage < 0) { percentage = 0; }
		
		if(this.options.html.hasClass('video')){
			this.options.player.volume = percentage;
		}
		else {
			BrowserSupp.getFlashMovieObject(player.options.player.get('id')).setVolume(percentage);
		}
		
		var perc = Math.round(percentage * 10);		
		this.options.volElms .each(function(elm, i){
			if (i <= perc){ elm.addClass('active'); }
			else { elm.removeClass('active'); }
		}, this);
	},
	toggleFullscreen: function(){
		if(this.options.html.hasClass('ipad')) {
			try {
				this.options.player.webkitEnterFullscreen();
			} catch(error) {
				onFullscreenChange();
			}
		} else if(this.options.html.hasClass('ie')) {
			if(!this.options.expanded) {
				this.options.expanded = true;
				this.options.html.setStyle('overflow', 'hidden');
			} else {
				this.options.expanded = false;
				this.options.html.setStyle('overflow', 'visible');
			}
		} else {
			if(!this.options.expanded) {
				this.options.expanded = true;
				this.options.fullScreen.setStyle('display', 'block');
				this.options.html.setStyle('overflow', 'hidden');
				this.options.wrapper.inject(this.options.fullScreen);
			} else {
				this.options.expanded = false;
				this.options.fullScreen.setStyle('display', 'none');
				this.options.html.setStyle('overflow', 'visible');
				this.options.wrapper.inject(this.options.defaultParent);
			}
		}
	},
	setDuration: function(duration){
		this.options.player.duration = duration;
	},
	showControls: function(){
		if($(document.html).hasClass('ie')) {
			this.options.controls.setStyle('display', 'block');
		} else {
			this.options.controls.set('tween', { duration: 300 }).fade(1);
		}		
	},	
	hideControls: function(){
		//if (Browser.safari){ return false; }
		if($(document.html).hasClass('ie')) {
			this.options.controls.setStyle('display', 'none');
		} else {
			this.options.controls.set('tween', { duration: 300 }).fade(0);
		}
	}
});

// News Archive AJAX
Tigi.NewsArchive = new Class({
	options: {
		wrapper: null,
		form: null,
		input: null,
		result: null,
		pager: null,
		active: 0,
		total: 0,
		ipp: 5,
		search: '',
		reset: true,
		allNewsUrl: '/news/archive',
		searchNewsUrl: '/news/search'
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.getNews();
	},
	addEvents: function(){		
		if (!this.options.form.retrieve('hasEvent')){
			this.options.form.addEvent('submit', function(e){
				e.stop();
				var value = this.options.input.get('value');
				if (
					(value.length > 0 && value != this.options.search) ||
					(value.length == 0 && value != this.options.search)
				){
					this.options.search = value;
					this.options.reset = true;
					this.activate(0);
				}
			}.bind(this));
		}
		
		this.options.pager.getElements('li.prev a, li.next a').each(function(elm, i){
			if (!elm.retrieve('hasEvent')){
				elm.addEvent('click', function(e){
					e.stop();
					if (elm.getParent('li').hasClass('prev')){
						this.prev();
					}
					else if (elm.getParent('li').hasClass('next')){
						this.next();
					}
				}.bind(this));
				elm.store('hasEvent', true);
			}
		}, this);
	},
	getNews: function(){
		var search = this.options.search.length > 0;
		var url = search ? this.options.searchNewsUrl : this.options.allNewsUrl;
		
		var vars = search ? { 'search': this.options.search} : {};
		vars.start = ((this.options.active * this.options.ipp) + 1)
		vars.end = ((this.options.active * this.options.ipp) + this.options.ipp);
		
		new Request.JSON({
			url: url,
			onComplete: function(json){
				this.create(json);
			}.bind(this)
		}).post(vars);
	},
	create: function(json){
		if (!json){ return false; }
		this.options.result.empty();
		this.options.total = Math.ceil(json.Total.toInt() / this.options.ipp);
		
		if (json.News.length > 0){
			json.News.each(function(news, i){
				var li = new Element('li');
				var a = new Element('a', { 'href': news.Url }).inject(li);
				var p = new Element('p', { 'class': 'title', 'html': news.Title }).inject(a);
				var span = new Element('span', { 'class': 'date', 'html': news.Date }).inject(a);
				li.inject(this.options.result);
			}, this);

			if (this.options.reset){
				this.options.pager.getElements('li.no').dispose();
				this.options.total.times(function(i){
					var li = new Element('li', { 'class': 'no' });
					var a = new Element('a', {
						'href': '#', 'html': (i + 1),
						'events': {
							click: function(e){
								e.stop();
								this.activate(i);
							}.bind(this)
						}
					}).inject(li);

					li.inject(this.options.pager.getElement('li.next'), 'before')
				}, this);
			}
			this.options.reset = false;
		}
		else {
			this.options.pager.getElements('li.no').dispose();
			var li = new Element('li', {
				'html': '<p class="title empty">' + this.options.result.get('data-empty') +  '</p>'
			}).inject(this.options.result);
		}
		
		this.setButtons();		
		this.addEvents();
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = 0;
			return false;
		}
		this.activate();
	},
	next: function(){
		++this.options.active;
		if (this.options.total - this.options.active < 1){
			this.options.active = this.options.total - 1;
			return false;
		}
		this.activate();
	},
	activate: function(i){
		if (typeof i != 'undefined'){ this.options.active = i; }
		this.getNews();
	},
	setButtons: function(){
		this.options.pager.getElements('li.no a').each(function(a, i){
			i == this.options.active ? a.addClass('active') : a.removeClass('active');
		}, this);
	}
});

// Article Slider Salon Page
Tigi.ArticleSlider = new Class({
	options: {
		wrapper: null,
		pager: null,
		articles: null,
		active: 0,
		next: 0,
		total: 0,
		wrapperWidth: 0,
		lblCurrent: null,
		lblTotal: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);		
		this.set();
		
		this.addEvents();
	},
	set: function(){
		this.setTotal();
		this.options.wrapperWidth = this.options.wrapper.getSize().x.toInt();
		this.options.articles.each(function(article, i){
			article.set('morph', {
				link: 'cancel',
				onComplete: function(){
					if (article.hasClass('active')){
						article.setStyles({
							'position': 'relative',
							'left': 0
						});
						this.options.wrapper.setStyle('height', 'auto');
					}
				}.bind(this)
			});
			if (i != this.options.active){
				article.setStyles({
					'position': 'absolute',
					'left': this.options.wrapperWidth,
					'top': 0,
					'width': this.options.wrapperWidth
				});
			}
		}, this);
	},
	setCurrent: function(){
		this.options.lblCurrent.set('text', this.options.active + 1);
	},
	setTotal: function(){
		this.options.total = this.options.articles.length;
		this.options.lblTotal.set('text', this.options.total);
	},
	addEvents: function(){
		this.options.pager.each(function(itm, i){
			itm.addEvent('click', function(e){
				e.stop();
				if (itm.getParent('li').hasClass('prev')){
					this.prev();
				}
				else {
					this.next();
				}
			}.bind(this));
		}, this);
	},
	prev: function(){
		--this.options.next;
		if (this.options.next < 0){
			this.options.next = 0;
			return false;
		}
		this.slide('prev');
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = this.options.total - 1;
			return false;
		}
		this.slide('next');
	},
	slide: function(type){
		var w = this.options.wrapper.getSize().x.toInt();
		this.options.wrapper.setStyle('height', this.options.articles[this.options.active].getSize().y.toInt());
		
		this.options.articles[this.options.active].setStyles({
			'position': 'absolute',
			'left': 0,
			'top': 0,
			'width': this.options.wrapperWidth
		}).removeClass('active').morph({
			'left': type == 'next' ? -w : w
		});
		
		this.options.articles[this.options.next].morph({
			'left': [(type == 'next' ? w : -w), 0]
		}).addClass('active');
		
		this.options.active = this.options.next;		
		this.setCurrent();
	}
});

// Twitter Feed Slider
Tigi.TweetSlider = new Class({
	options: {
		items: null,
		time: null,
		active: 0,
		next: 0,
		total: 0,
		periodical: 7000
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.items.length;
		
		var self = this;
		this.options.items.set('tween', {
			onComplete: function(){
				if (this.element.getStyle('opacity') == 0){
					this.element.setStyle('display', 'none');
					self.show();
				}
			}
		}).setStyle('display', 'none').fade('hide');
		
		this.show();
		if (this.options.total > 1){
			this.start();
		}
	},
	start: function(){
		this.next.periodical(this.options.periodical, this);
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = 0;
		}
		this.hide();
	},
	hide: function(){
		this.options.items.fade(0);
	},
	show: function(){
		this.options.items[this.options.next].setStyle('display', 'block').fade(1);
		this.options.active = this.options.next;
		
		this.options.time.set('text', this.options.items[this.options.next].get('data-time'));
	}
});

// Brands Full Width Buttons
Tigi.Brands = new Class({
	options: {
		active: null,
		next: null,
		items: null,
		defaultItems: null,
		slides: [],
		pushboxes: [],
		scroll: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);		
		this.options.scroll = new Fx.Scroll(window);
		
		this.addEvents();
	},
	addEvents: function(){
		this.options.items.each(function(itm, i){			
			if (itm.getElement('.pushbox')){
				this.options.pushboxes.push(new Tigi.Pushbox({
					wrapper: itm.getElement('.pushbox'),
					items: itm.getElements('.pushbox ul.items li'),
					buttons: itm.getElements('.pushbox nav ul li a')
				}));
				this.options.pushboxes[i].hide('set');
			}
			
			this.options.slides.push(new Fx.Slide(itm.getElement('.info'), {
				duration: 400,
				onStart: function(){
					!this.options.slides[i].open ? itm.addClass('active') : itm.removeClass('active');
				}.bind(this),
				onComplete: function(){
					if (!this.options.defaultItems[i].retrieve('hover')){
						this.options.defaultItems[i].fireEvent('mouseleave');
					}
					if (scroll){ scroll.reCalc(); }
				}.bind(this)
			}).hide());
			
			itm.getElements('a.toggle').addEvent('click', function(e){
				if (e){ e.stop(); }
				this.toggleOther(i);
				this.options.slides[i].toggle();
				(function(){
					this.options.scroll.start(0, this.options.items[i].getPosition(document.body).y - 69);
				}).delay(400, this);
				return false;
			}.bind(this));
		}.bind(this));
		
		this.options.defaultItems.each(function(itm, i){
			itm.getElement('.color').setStyle('display', 'block').fade('hide').set('tween', { duration: 400, link: 'cancel' });
			this.imageEvents(itm);
		}.bind(this));
	},
	imageEvents: function(itm){
		itm.addEvents({
			mouseenter: function(){
				itm.store('hover', true).addClass('hover');
				itm.getElement('.color').fade(1);
			}.bind(this),
			mouseleave: function(){
				itm.store('hover', false).removeClass('hover');
				if (!itm.getParent().hasClass('active')){
					itm.getElement('.color').fade(0);
				}
			}.bind(this),
			click: function(){
				if (!itm.getParent().hasClass('active')){
					itm.getElement('a').fireEvent('click');
				}
			}
		});
	},
	toggleOther: function(i){
		var open = this.options.slides[i].open;
		this.options.items.each(function(itm, j){
			if (i != j){
				if (this.options.slides[j].open){
					this.options.slides[j].slideOut();
				}
				this.options.defaultItems[j].fireEvent('mouseleave');
				!open ? itm.fade(.2) : itm.fade(1);
				itm.getElement('a.toggle').set('text', 'more information');
				
				this.options.pushboxes[j].hide();
			}
			else {
				itm.getElement('a.toggle').set('text', (!this.options.slides[j].open ? 'close' : 'more information'));
				itm.fade(1);
				
				if (this.options.slides[j].open){
					this.options.pushboxes[j].hide();
				}
				else {
					this.options.pushboxes[j].show();
				}
			}
		}.bind(this));
	}
});

// Pushbox Slider
Tigi.Pushbox = new Class({
	options: {
		wrapper: null,
		items: null,
		buttons: null,
		total: 0,
		active: 0,
		next: 0,
		periodical: 6000,
		timer: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.initItems();

		this.start();
		this.addEvents();
	},
	initItems: function(){
		this.options.items.each(function(itm, i){
			itm.setStyle('display', 'block').fade('hide').set('morph', { duration: 600, link: 'cancel' });
			if (i == this.options.active){
				itm.fade(1);
			}
		}.bind(this));
		this.options.total = this.options.items.length;
		
		this.options.wrapper.set('tween', { duration: 400, link: 'cancel' });
	},
	addEvents: function(){
		this.options.buttons.each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				if (i != this.options.active){
					this.activate(i);
				}
			}.bind(this));
		}.bind(this));
		
		var nav = this.options.wrapper.getElement('nav').fade('hide');
		this.options.wrapper.addEvents({
			mouseenter: function(){ this.stop(); nav.fade(1); }.bind(this),
			mouseleave: function(){	this.restart(); nav.fade(0); }.bind(this)
		});
	},
	start: function(){
		this.options.timer = this.next.periodical(this.options.periodical, this);
	},
	stop: function(){
		clearInterval(this.options.timer);
	},
	restart: function(){
		this.stop();
		this.start();
	},
	activate: function(i){
		this.options.next = i;
		this.slide();
		this.restart();
	},
	prev: function(){
		--this.options.next;
		if (this.options.next < 0){
			this.options.next = this.options.total - 1;
		}
		this.slide();
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = 0;
		}
		this.slide();
	},
	slide: function(){
		var pos = ($(window).getSize().x / 3),
			method = 'right';
		if (this.options.active < this.options.next){
			method = 'left';
		}		
		
		this.options.items[this.options.active].morph({
			'left': (method == 'left' ? -pos : pos)
		}).fade(0);
		this.options.items[this.options.next].morph({
			'left': [(method == 'left' ? pos : -pos), 0]
		}).fade(1);
		
		this.options.active = this.options.next;
		this.setNav();
	},
	setNav: function(){
		this.options.buttons.removeClass('active');
		this.options.buttons[this.options.active].addClass('active');
	},
	hide: function(type){
		this.stop();
		var h = this.options.wrapper.getSize().y.toInt();
		if (type == 'set'){
			this.options.wrapper.setStyle('top', -h);
			return false;
		}
		this.options.wrapper.tween('top', -h);
	},
	show: function(){
		this.start();
		this.options.wrapper.tween('top', 0);
	}
});

// Scrollpage, for scrolling pages with nav buttons
Tigi.Scrollpage = new Class({
	options: {
		active: null,
		wrapper: null,
		nav: null,
		container: window,
		buttons: null,
		scroll: null,
		target: [],
		percentage: 30
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.scroll = new Fx.Scroll(this.options.container);
		this.options.container = $(this.options.container);
		
		this.addEvents();
	},
	reCalc: function(){
		this.options.buttons.each(function(btn, i){
			var target = $(btn.get('href').substr(1, btn.get('href').length - 1));
			if (target){
				this.setDimensions(target);
			}
		}, this);
		this.options.container.fireEvent('scroll');
	},
	addEvents: function(){
		if (!this.options.nav){ return false; }
		if (this.options.nav.hasClass('fixed-sub')){
			this.fixed = true;
			this.pos = this.options.nav.getPosition($(document.body)).y;
		}
		
		this.options.buttons.each(function(btn, i){
			var target = $(btn.get('href').substr(1, btn.get('href').length - 1));
			if (target){
				this.options.target.push(target);
				this.setDimensions(target);
				this.setDimensions.delay(1000, this, target);
			}
			btn.addEvent('click', function(e){
				e.stop();
				this.toElement(this.options.target[i]);
			}.bind(this));
		}, this);
				
		this.options.container.addEvent('scroll', function(){
			if (this.fixed){
				if (this.options.container.getScroll().y >= this.pos - 65){
					this.options.nav.setStyles({
						'position': 'fixed', 'top': 65
					});
				}
				else {
					this.options.nav.setStyles({
						'position': 'absolute', 'top': this.pos - 65
					});
				}
			}
			
			var m = this.options.container.getScroll().y + (this.options.container.getSize().y.toInt() / 100 * this.options.percentage);
			if (this.options.container.getScroll().y + this.options.container.getSize().y.toInt() >= $(document.body).getScrollSize().y.toInt() - 2){
				var href = this.options.buttons.getLast().get('href');
				m = $(href.substr(1, href.length - 1)).retrieve('max').toInt();
			}
			this.find(m);
		}.bind(this)).fireEvent('scroll');
	},
	setDimensions: function(target){
		target.store('min', target.getPosition($(document.body)).y.toInt());
		target.store('max', target.retrieve('min').toInt() + target.getSize().y.toInt());
	},
	find: function(m){
		var found = 0;
		this.options.target.each(function(target, i){
			if (m >= target.retrieve('min') && m <= target.retrieve('max')){	
				this.activate(i);
				++found;
			}
		}, this);
		if (found == 0){
			this.deactivate();
		}
	},
	toElement: function(to){
		if (!to){ return false; }
		var y = to.getPosition($(document.body)).y.toInt();
		this.to(y);
	},
	to: function(y){
		this.options.scroll.start(0, y - 65);
	},
	activate: function(key){
		this.options.buttons.each(function(btn, i){
			if (i == key){
				btn.addClass('active');
			}
			else if(btn.hasClass('active')){
				btn.removeClass('active');
			}
		});
	},
	deactivate: function(){
		this.options.buttons.each(function(btn, i){
			btn.removeClass('active');
		});
	}
});

// Inner Page Scroll Links
Tigi.InnerPageScroll = new Class({
	options: {
		links: null,
		container: document.body,
		scroll: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.scroll = new Fx.Scroll(this.options.container);
		
		this.addEvents();
	},
	addEvents: function(){
		this.options.links.each(function(link, i){
			link.addEvent('click', function(e){
				e.stop();
				this.toElement(link.get('href'));
			}.bind(this));
			
			if (link.hasClass('scroll-content')){
				this.addWindowScroll(link);
			}
		}, this);
	},
	addWindowScroll: function(link){
		if ($(window).getSize().y >= $(document.body).getScrollSize().y) {
			link.setStyle('display', 'none');
			return false;
		}
		var h = 0;
		link.set('morph', { duration: 350 });
		$(window).addEvent('scroll:once', function(e){
			$$('body > header, #pushbox, #visual, .text-visual figure.picture, article.content-dark.intro-text, article.education-intro').each(function(elm, i){
				h += elm.getSize().y.toInt();
			});
			link.morph({ 'top': -h, 'opacity': 0 });
		}.bind(this));
	},
	toElement: function(target){
		var to = $(target.substr(1, target.length - 1));
		if (!to){ return false; }
		var y = to.getPosition($(document.body)).y.toInt();
		this.to(y);
	},
	to: function(y){
		this.options.scroll.start(0, y - 65);
	}
});

// Pager for Maps
Tigi.Pager = new Class({
	options: {
		active: 0,
		total: 0,
		pageTotal: 0,
		ipp: 5,
		showNavItems: 4,
		items: null,
		pagerWrapper: null,
		pagerButtons: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.options.total = this.options.items.length;
		this.options.pageTotal = Math.ceil(this.options.total / this.options.ipp);
		
		this.createPager();
	},
	createPager: function(){
		this.options.pageTotal.times(function(i){
			new Element('li', {
				'html': '<a class="no" href="#' + (i + 1) + '">' + (i + 1) + '</a>'
			}).inject(this.options.pagerWrapper.getElement('li.next'), 'before');
		}, this);
		
		this.addEvents();
		this.show();
	},
	addEvents: function(){
		this.options.pagerButtons = this.options.pagerWrapper.getElements('li a.no');
		this.options.pagerWrapper.getElements('li a').each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				if (btn.getParent().hasClass('prev')){
					this.prev();
				}
				else if (btn.getParent().hasClass('next')){
					this.next();
				}
				else {
					this.activate(btn.get('text').toInt() - 1);
				}
			}.bind(this));
		}, this);
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = 0;
			return false;
		}
		this.show();
	},
	next: function(){
		++this.options.active;
		if (this.options.active >= this.options.pageTotal){
			this.options.active = this.options.pageTotal - 1;
			return false;
		}
		this.show();
	},
	activate: function(i){
		this.options.active = i;
		this.show();
	},
	show: function(){
		var start = this.options.active * this.options.ipp;
		this.options.items.each(function(itm, i){
			if (i >= start && i < start + this.options.ipp){
				itm.setStyle('display', 'block');
			}
			else {
				itm.setStyle('display', 'none');
			}
		}, this);
		
		this.activateButton();
	},
	activateButton: function(){
		this.options.pagerButtons.removeClass('active');
		if (this.options.pagerButtons[this.options.active]){
			this.options.pagerButtons[this.options.active].addClass('active');
		}
		
		if (this.options.pageTotal > this.options.showNavItems){
			this.setButtonView();
		}
	},
	setButtonView: function(){
		var half = this.options.showNavItems / 2,
			start = this.options.active - half,
			end = this.options.active + half,
			diff = 0;
		
		if (start < 0){
			diff = 0 - start;
			start = 0;
			end += diff;
		}
		else if (end >= this.options.pageTotal){
			diff = end - this.options.pageTotal + 1;
			start -= diff;
			end = this.options.pageTotal - 1;
		}
		
		this.options.pagerButtons.each(function(btn, i){
			if (i >= start && i <= end){
				btn.getParent().setStyle('display', 'inline');
			}
			else {
				btn.getParent().setStyle('display', 'none');
			}
		});
	}
});

// Load Formulas on Change Dropdown
Tigi.LoadFormulas = function(wrapper){
	$$(wrapper).each(function(wrapper, i){
		var list = $$('.formula-list')[0];
		wrapper.getElement('input').addEvent('change', function(){
			list.empty().addClass('loading');
			var loaded = 0, total = 0, delay = 0;
			var request = new Request.JSON({
				'url': 'Formulas',
				onComplete: function(json){
					total = json.length;
					json.each(function(image, i){						
						var li = new Element('li').setStyle('display', 'none');
						var a = new Element('a', { 'href': '#', 'events': {
							click: function(e){
								e.stop();
								this.toggleClass('active');
							}
						} }).inject(li);
						new Element('img', {
							'src': image + '.jpg', 'class': 'default', 'alt': image
						}).inject(a);						
						new Element('img', {
							'src': image + '.png', 'class': 'hover', 'alt': image
						}).inject(a);						
						li.inject(list);
						
						new Asset.image(image + '.jpg', { 
							onLoad: function(){
								++loaded;
								if (loaded >= total){
									list.removeClass('loading');
									list.getElements('li').each(function(listItem, j){
										(function(){
											listItem.setStyle('display', 'block').fade('hide').fade(1);
										}).delay(delay += 50);
									});
								}
							}
						});
					});
				}
			}).post({ 'category': this.get('value') });
		}).fireEvent('change');
	});
}

// Formulas Click toggleClass Hover
Tigi.Formulas = function(elms){
	if (!$$(elms)[0]){ return false; }
	var parent = $$(elms)[0].getParent('ul');
	if (parent.hasClass('formula-more-info')){ return false; }
	$$(elms).addEvent('click', function(e){
		e.stop();
		this.toggleClass('active');
	})
}

// Formulas on Click show More info
Tigi.FormulasMoreInfo = function(elms){
	var anim = false,
		selectedElms = $$(elms),
		slides = {},
		ipr = 6;
	selectedElms.each(function(li, i){
		if (li.getElement('.swatch-more-info')){
			li.getElement('.swatch-more-info').setStyle('display', 'block');
			li.set('tween', { link: 'cancel' });
			slides[i] = new Fx.Slide(li.getElement('.swatch-more-info'), {
				link: 'cancel',
				onComplete: function(){
					var elm = li;
					if (!this.open){ elm = li.getElement('div'); }
					anim = false;
					new Fx.Scroll($(window)).start(0, elm.getPosition($(document.body)).y - 105);
					if (scroll){
						scroll.reCalc();
					}
				}
			}).hide();
			slides[i].element.getParent().setStyles({ 'background': '#ffffff', 'z-index': 1, 'left': '50%', 'margin-left': -480 });
			slides[i].element.setStyles({ 'position': 'relative', 'top': 0 });
			li.getElements('> a, a.close').addEvent('click', function(e){
				e.stop();
				if (anim){ return false; }
				var row = Math.ceil((i + 1) / ipr);
				anim = true;
				if (slides[i].open){
					slides[i].slideOut();
					
					var mb = 0;
					var elm = selectedElms[row * ipr - 1];
					if (!elm){
						elm = selectedElms.getLast();
						if (Browser.ie7){ elm = li.getParent(); mb = 92; }
					}
					elm.tween('marginBottom', mb);
					li.getElement('> a').removeClass('active-sub');
				}
				else {
					Object.each(slides, function(slide, j){
						if (slide != slides[i] && slide.open){
							var mb = 0;
							var row2 = Math.ceil((j.toInt() + 1) / 6);							
							slide.slideOut();
							var elm = selectedElms[row2 * ipr - 1];
							if (!elm){
								elm = selectedElms.getLast();
								if (Browser.ie7){ elm = li.getParent(); mb = 92; }
							}
							elm.tween('marginBottom', mb);
						}
					});
					slides[i].slideIn();
					
					selectedElms.each(function(subElm, j){
						if (j == i){
							subElm.getElement('> a').addClass('active-sub');
						}
						else {
							subElm.getElement('> a').removeClass('active-sub');
						}
					});
					
					var mb = slides[i].offset;
					var elm = selectedElms[row * ipr - 1];
					if (!elm){
						elm = selectedElms.getLast();
						if (Browser.ie7){ elm = li.getParent(); mb += 92; }
					}
					elm.tween('marginBottom', mb);
				}
			});
		}
	});
}

// Toggle an Element on Click
Tigi.ToggleElm = function(elms){
	var j = 0;
	elms.each(function(elm, i){
		elm.addEvent('click', function(e){
			if (e){ e.stop(); }
			if (player){
				if (elm.hasClass('pauseVideo')){
					if (player.options.expanded){
						player.toggleFullscreen();
					}
					player.pauseVideo();
				}
				else if (elm.hasClass('playVideo')){
					player.playVideo();
				}
			}
			var target = $(elm.get('href'));
			if (target){
				target.getStyle('visibility') == 'hidden' ? elm.removeClass('active') : elm.addClass('active');
				target.setStyles({
					'visibility': (target.getStyle('visibility') == 'hidden' ? 'visible' : 'hidden'),
					'top': (target.getStyle('visibility') == 'hidden' ? 0 : -1000)
				});
			}
			return false;
		});
		if (j == 0 && elm.hasClass('pauseVideo')){ ++j; elm.fireEvent('click'); }
	});
}

Tigi.ToggleElmDefault = function(elms){
	var j = 0;
	elms.each(function(elm, i){
		elm.addEvent('click', function(e){
			if (e){ e.stop(); }
			
			var target = $(elm.get('href'));
			if (target){
				target.getStyle('display') == 'none' ? elm.removeClass('active') : elm.addClass('active');
				target.setStyles({
					'display': (target.getStyle('display') == 'none' ? 'block' : 'none')
				});
			}
			return false;
		});
	});
}

// Slide an Element in/out on Click
Tigi.SlideElm = function(elms){
	elms.each(function(elm, i){
		var target = $(elm.get('data-slide')).setStyle('display', 'none');
		elm.addEvent('click', function(e){
			e.stop();
			target.setStyle('display', 'block');
			if (elm.hasClass('hideElm')){
				elm.getParent('.' + elm.get('data-hide')).setStyle('display', 'none');
			}
			new Fx.Scroll(document.body).toElement(target);
			if (scroll){ scroll.reCalc(); }
		});
		if (target.hasClass('open')){
			target.setStyle('display', 'block');
			new Fx.Scroll(document.body).toElement(target);
		}
	});
}

// Toggle Other Person Element in Register Form
Tigi.ToggleFormRegistration = function(elms, toggleItm, value){
	if (!toggleItm || elms.length < 1){ return false; }
	
	var dur = 400;
	var slide = new Fx.Slide(toggleItm, {
		link: 'cancel', duration: dur,
		onComplete: function(){
			if (!this.open){
				this.element.setStyle('overflow', 'visible');
				this.element.getParent().setStyle('overflow', 'visible');
			}
			else {
				this.element.setStyle('overflow', 'hidden');
				this.element.getParent().setStyle('overflow', 'hidden');
			}
		}
	});
	
	var show = false, ie7 = Browser.ie7;
	elms.each(function(elm, i){
		elm.addEvent('change', function(){
			if (!elm.get('checked')){ return false; }
			if (elm.get('value') == value){
				if (ie7){ toggleItm.setStyle('display', 'block'); }
				else { slide.slideIn(); }
			}
			else {
				if (slide.open){
					if (ie7){
						toggleItm.setStyle('display', 'none');
					}
					else {
						slide.element.setStyle('overflow', 'hidden');
						slide.element.getParent().setStyle('overflow', 'hidden');
						slide.slideOut();
					}
					slide.element.getElements('input').set('value', '');
				}
			}
		});
		
		if (elm.get('checked') && elm.get('value') == value){ show = true; }
	});
	
	if (!show){
		if (ie7){ toggleItm.setStyle('display', 'none'); }
		else { slide.hide(); }
	}
	else {
		if (!ie7){
			slide.element.setStyle('overflow', 'visible');
			slide.element.getParent().setStyle('overflow', 'visible');
		}
	}
}
Tigi.ToggleFormRegistrationComplete = function(slide, delay){
	(function(){
		if (!slide.open){
			//alert('test');
			slide.element.setStyle('overflow', 'visible');
			slide.element.getParent().setStyle('overflow', 'visible');
		}
		else {
			//alert('test1');
			slide.element.setStyle('overflow', 'hidden');
			slide.element.getParent().setStyle('overflow', 'hidden');
		}
	}).delay(delay);
}

// Team List Mouseevents
Tigi.Team = function(elms, fixedHeight){
	elms.each(function(elm, i){
		var textElm = elm.getElement('.text').set('tween', { duration: 100, link: 'cancel' });
		elm.store('minHeight', textElm.getSize().y);
		elm.addEvents({
			mouseenter:function(){
				if (!elm.retrieve('maxHeight')){
					var maxHeight = textElm.measure(function(){
						return this.getScrollSize().y;
					});
					elm.store('maxHeight', (fixedHeight ? fixedHeight : maxHeight));
				}
				if (elm.retrieve('timer')){ clearInterval(elm.retrieve('timer')); }
				elm.setStyle('z-index', 2);
				textElm.tween('height', elm.retrieve('maxHeight'));
				elm.getParent().addClass('hover');
			},
			mouseleave: function(){
				elm.store('timer', (function(){ elm.setStyle('z-index', ''); }).delay(150));
				textElm.tween('height', elm.retrieve('minHeight'));
				elm.getParent().removeClass('hover');
			}
		});
	});
}

// Init Accordions
Tigi.Accordion = function(selector){
	$$(selector).each(function(wrap, i){
		var init = 0, scrollTo = false;
		if (document.location.hash){
			wrap.getElements('dt').each(function(dt, j){
				if (dt.get('data-hash') == document.location.hash.replace('#', '')){
					init = j;
					scrollTo = true;
				}
			});
			if (scrollTo){
				new Fx.Scroll($(window)).start(0, $('product-usage').getPosition($(document.body)).y - 65);
			}
		}
		if (wrap.get('data-show')){
			init = wrap.get('data-show').toInt();
		}
		new Fx.Accordion(wrap.getElements('dt'), wrap.getElements('dd > div'), {
			show: init,
			alwaysHide: true,
			onActive: function(toggler, elm){
				toggler.addClass('active');
			},
			onBackground: function(toggler, elm){
				toggler.removeClass('active');
			},
			onComplete: function(){
				if (scroll){
					scroll.reCalc();
				}
				
				var y = 0;
				this.togglers.each(function(toggler, i){
					if (toggler.hasClass('active')){
						y = toggler.getPosition($(document.body)).y;
					}
				});
				if (y > 0){
					new Fx.Scroll($(window)).start(0, y - 105);
				}
			}
		});
	});
}

// Equal Column Heights
Tigi.EqualColumns = function(elms){
	(function(){
		var h = 0;
		elms.each(function(elm, i){ h = Math.max(h, elm.getSize().y.toInt()); });
		elms.setStyle('height', h);
	}).delay(500);
}

// Activate Label on Checkbox Change
Tigi.ActiveLabel = function(inputs, labels){
	inputs.each(function(inp, i){
		inp.addEvent('change', function(){
			var lbl = labels[i];
			labels.removeClass('active');
			inp.get('checked') ? lbl.addClass('active') : lbl.removeClass('active');
		}).fireEvent('change');
	});
}

// Set Full Height from Element
Tigi.FullHeight = function(wrapper){
	var minus = wrapper.getStyle('paddingTop').toInt() + wrapper.getStyle('paddingBottom').toInt(),
		scrollSize = wrapper.getScrollSize().y;
	$(window).addEvent('resize', function(){
		var counted = this.getSize().y.toInt() - minus - 97;
		wrapper.setStyle('height', Math.max(scrollSize - 65, counted));
	}).fireEvent('resize');
}

// Custom Select Boxes
BrowserSupp.Select = new Class({
    options: {
        select: null,
        wrapper: null,
        list: null,
        items: [],
        label: null,
        input: null,
        maxHeight: 200,
        open: true,
        id: 0,
        click: false,
        lastKey: '',
        findKey: 0
    },
    Implements: [Options, Events],
    initialize: function (select, id, options) {
        this.setOptions(options);
        this.options.select = select;
        this.options.id = id;

        this.create();
    },
    create: function () {
        var w = this.options.select.measure(function () {
            return this.getSize().x;
        });
        this.options.wrapper = new Element('div', {
            'class': 'custom-select ' + this.options.select.get('class'),
            'styles': {
                'float': this.options.select.getStyle('float'),
                'width': w,
                'margin': this.options.select.getStyle('margin')
            },
            'events': {
                click: function () {
                    this.options.click = true;
                } .bind(this)
            }
        }).wraps(this.options.select);

        $(document.body).addEvents({
            click: function () {
                if (!this.options.click) { this.close(); }
                this.options.click = false;
            } .bind(this),
            keydown: function (e) {
                if (this.options.open) {
                    switch (e.key) {
                        case 'down': 
                            {
                                if (this.options.list.getElement('li.hover')) {
                                    e.stop();
                                    var next = this.options.list.getElement('li.hover').getNext();
                                    if (next) { next.fireEvent('mouseenter'); }
                                    else { this.options.list.getElement('li').fireEvent('mouseenter'); }
                                    this.options.findKey = -1;
                                    this.scrollTo();
                                }
                                break;
                            }
                        case 'up': 
                            {
                                if (this.options.list.getElement('li.hover')) {
                                    e.stop();
                                    var prev = this.options.list.getElement('li.hover').getPrevious();
                                    if (prev) { prev.fireEvent('mouseenter'); }
                                    else { this.options.list.getLast('li').fireEvent('mouseenter'); }
                                    this.options.findKey = -1;
                                    this.scrollTo();
                                }
                                break;
                            }
                        case 'enter': 
                            {
                                if (this.options.list.getElement('li.hover')) {
                                    e.stop();
                                    this.options.list.getElement('li.hover').fireEvent('click');
                                }
                                break;
                            }
                        default: 
                            {
                                var re = /^[a-z0-9]$/;
                                if (re.test(e.key)) {
                                    this.filter(e.key);
                                }
                                break;
                            }
                    }
                }
            } .bind(this),
            mouseleave: function () {
                if (this.options.open) { this.close(); }
            } .bind(this)
        });

        this.options.input = new Element('input', {
            'type': 'hidden',
            'name': this.options.select.get('name'),
            'id': (this.options.select.get('id') ? this.options.select.get('id') : null)
        }).inject(this.options.wrapper);

        this.options.label = new Element('a', {
            'href': '#',
            'html': '<span></span><span class="arrow"><strong>&rsaquo;</strong></span>',
            'events': {
                click: function (e) {
                    e.stop();
                    this.toggle();
                } .bind(this)
            }
        }).inject(this.options.wrapper);

        this.options.list = new Element('ul').inject(this.options.wrapper);
        this.options.select.getElements('option').each(function (option, i) {
            this.options.items.push(new Element('li', {
                'text': option.get('text'),
                'data-value': option.get('value'),
                'data-selected': option.get('selected'),
                'events': {
                    click: function () {
                        this.select(this.options.items[i]);
                    } .bind(this),
                    mouseenter: function () {
                        this.options.list.getElements('li').removeClass('hover');
                        this.options.items[i].addClass('hover');
                    } .bind(this),
                    mouseleave: function () {
                    }
                }
            }).inject(this.options.list));

            if (option.get('selected')) {
                this.options.items[i].fireEvent('click');
            }
        } .bind(this));

        if (this.options.items[0]) {
            this.options.maxHeight = this.options.items[0].getStyle('line-height').toInt() * 10;
        }

        this.setValidation();

        this.options.select.dispose();
    },
    toggle: function () {
        this.options.open ? this.close() : this.open();
    },
    open: function () {
        var windowHeight = $(document.body).getScrollSize().y.toInt();

        Tigi.HideSelects(this.options.id);

        this.options.items.each(function (itm, i) {
            if (itm.get('data-selected') == 'true') { itm.addClass('hover'); }
        });

        this.options.list.setStyle('display', 'block');
        this.scrollTo();
        this.options.open = true;

        if (this.options.list.getScrollSize().y.toInt() > this.options.maxHeight) {
            this.options.list.setStyle('height', this.options.maxHeight);
        }

        var listPos = this.options.list.getPosition($(document.body)).y,
			listHeight = this.options.list.getSize().y.toInt();

        if (listPos + listHeight > windowHeight) {
            this.options.list.setStyle('top', -listHeight).addClass('top');
        }
    },
    close: function () {
        this.options.list.setStyle('display', 'none');
        this.options.open = false;

        if (this.options.list.hasClass('top')) {
            this.options.list.setStyle('top', this.options.label.getSize().y.toInt()).removeClass('top');
        }

        this.options.list.getElements('li').removeClass('hover');
    },
    scrollTo: function (elm) {
        if (!elm) { elm = this.options.list.getElement('li.hover'); }
        if (!elm) { return false; }
        var pos = elm.getPosition(this.options.list).y + this.options.list.getScroll().y;
        this.options.list.scrollTo(0, (pos >= this.options.list.getSize().y.toInt() ? pos : 0));
    },
    select: function (itm) {
        this.options.findKey = 0;
        this.options.label.getElement('span').set('text', itm.get('text'));

        this.options.label.getElement('span').removeClass('selected');
        if (itm.get('data-value').length > 0 && (itm.get('data-value').toInt().toString() == 'NaN' || itm.get('data-value').toInt() >= 0)) {
            this.options.label.getElement('span').addClass('selected');
        }
        var value = itm.get('data-value');
        this.options.input.set('value', value).fireEvent('change');

        this.options.items.each(function (item, i) {
            item.set('data-selected', false);
        });
        itm.set('data-selected', true);
        this.fireEvent('change', value);
        this.close();
    },
    selected: function(){
        return this.options.input.get('value');
    },
    filter: function (key) {
        var res = this.findItems(key);

        if (res[this.options.findKey]) {
            res[this.options.findKey].fireEvent('mouseenter');
            this.scrollTo(res[this.options.findKey]);
        }
    },
    findItems: function (inp) {
        if (inp == this.options.lastKey && this.found) {
            ++this.options.findKey;
        }
        else {
            this.options.lastKey = inp;
            this.options.findKey = 0;

            this.found = this.options.items.filter(function (item, i) {
                return item.get('text').substr(0, inp.length).toLowerCase() == inp;
            } .bind(this));
        }

        if (this.found[0]) {
            if (this.found[this.options.findKey]) {
                return this.found;
            }
            else if (this.found[0]) {
                this.options.findKey = 0;
                return this.found;
            }
            return false;
        }
        else {
            return false;
        }
    },
    resetKey: function () {
        this.options.lastKey = '';
    },
    setValidation: function () {
        var val = 0;
        ['required', 'number', 'range', 'range-min', 'range-max'].each(function (validator, i) {
            if (this.options.select.get('data-val-' + validator)) {
                this.options.input.set('data-val-' + validator, this.options.select.get('data-val-' + validator));
                ++val;
            }
        }, this);
        if (val > 0) { this.options.input.addClass('validate-custom-select'); }
    },
    show: function(){
        this.options.wrapper.setStyle('display', 'block');
    },
    hide: function(){
        this.options.wrapper.setStyle('display', 'none');
    }
});

Tigi.HideSelects = function(id){
	selects.each(function(select, i){
		if (i != id){
			select.close();
		}
	});
}

// Custom Checkboxes & Radio Buttons
BrowserSupp.Checkbox = new Class({
	options: {
		elements: null
	},
	Implements: Options,
	initialize: function(elements, options){
		this.setOptions(options);
		
		this.options.elements = elements;		
		if (!this.options.elements){
			this.setElements();
		}
		this.createCustom();
	},
	setElements: function(){
		this.options.elements = $$('input[type=checkbox], input[type=radio]');
	},
	createCustom: function(){
		var self = this;
		this.options.elements.each(function(element, key){
			if (!element.get('custom')){
				var type = element.get('type');
				var customElement = new Element('a', { 'class': 'custom-' + type }).inject(element, 'after');
				var sameElements = $$('input[type=' + type + '][name="' + element.get('name') + '"]');
				
				element.get('checked') ? customElement.addClass('active') : null;				
				element.addEvent('change', function(){
					if (this.get('checked')){
						customElement.addClass('active');
						self.resetOther(type, sameElements);
					}
					else {customElement.removeClass('active');}
				});
				customElement.addEvents({
					mouseenter: function(){ this.addClass('hover'); },
					mouseleave: function(){ this.removeClass('hover'); },
					click: function(e){
						e.stop();
						if (element.get('checked') && type != 'radio'){element.set('checked', false);}
						else {
							self.uncheckOther(type, element, sameElements);
							element.set('checked', true);
						}
						element.fireEvent('change');
					}
				});
				element.setStyle('display', 'none').fireEvent('change');
				element.set('custom', true);
			}
		});
	},
	resetOther: function(type, sameElements){
		if (type == 'radio' && sameElements.length > 1){
			sameElements.each(function(radio, key){
				if (!radio.get('checked') && radio.getNext('a.custom-' + type)){
					radio.getNext('a.custom-' + type).removeClass('active');
				}
			});
		}
	},
	uncheckOther: function(type, element, sameElements){
		if (type == 'radio'){
			sameElements.each(function(el, i){
				el != element ? element.set('checked', false) : null;
			});
		}
	}
});

// Input Placeholder Support
BrowserSupp.Placeholder = function(input){
	if (typeof input == 'undefined'){ input = 'input[type=text], textarea'; }
	var inputElm = new Element('input');
	if (!inputElm.property('placeholder')){
		$$(input).each(function(inp, i){
			if (inp.get('placeholder') && !inp.property('placeholder')){
				var placeholder = inp.get('placeholder');
				inp.addEvents({
					focus: function(){
						inp.get('value') == placeholder ? inp.set('value', '').removeClass('noInp') : null;
					},
					blur: function(){
						!inp.get('value') || inp.get('value') == placeholder ? inp.set('value', placeholder).addClass('noInp') : null;
					}
				}).fireEvent('blur');
				inp.getParent('form').addEvent('submit', function(){
					inp.get('value') == placeholder ? inp.set('value', '') : null;
				});
			}
		});
	}
	return true;
}

BrowserSupp.Pseudos = function(elms, type, content){
	if (Browser.ie6 || Browser.ie7 || Browser.ie8){
		switch (type){
			default:
			case 'both': $$(elms).each(function(a, i){ new Element('span', { 'class': 'elm-before' }).inject(a, 'top'); new Element('span', { 'class': 'elm-after' }).inject(a); }); break;
			case 'before': $$(elms).each(function(a, i){ new Element('span', { 'class': 'elm-before', 'html': (content ? content : '') }).inject(a, 'top'); }); break;
			case 'after': $$(elms).each(function(a, i){ new Element('span', { 'class': 'elm-after' }).inject(a); }); break;
		}
	}
	return true;
}

// Get Flash Video Object
BrowserSupp.getFlashMovieObject = function(movieName){
	if (window.document[movieName]){
		return window.document[movieName];
	}
	if (navigator.appName.indexOf('Microsoft Internet') == -1){
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName]; 
	}
	else {
		return document.getElementById(movieName);
	}
}

function videoTimeUpdate(time){
	if (!player){ return false; }
	player.videoTimeUpdate(time);
}
function updateVideoDuration(duration){
	if (!player){ return false; }
	player.setDuration(duration);
}
function playerInitDone(){
	if (!player){
		playerInitDone.delay(250);
		return false;
	}
	BrowserSupp.getFlashMovieObject(player.options.player.get('id')).setVolume(1);
	player.pauseVideo();
}
function playerEnded(evt){
	_gaq.push(evt);
}

Element.implement({
	property: function(prop){
		var elm = document.createElement(this.get('tag'));
		return prop in elm;
	}
});